package just.stuff.morsels.ui;


import javax.servlet.http.Cookie;

import just.stuff.morsels.MorselApplication;
import just.stuff.morsels.MorselSession;
import just.stuff.morsels.data.BerkeleyDataSource;
import just.stuff.morsels.objects.Morsel;
import just.stuff.morsels.objects.User;
import just.stuff.morsels.ui.morsel.MorselPage;
import just.stuff.morsels.ui.search.SearchPanel;
import just.stuff.morsels.ui.user.LoginLink;
import just.stuff.morsels.ui.user.LogoutLink;
import just.stuff.morsels.ui.user.UserPageLink;

import org.apache.wicket.RequestCycle;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.protocol.http.WebRequest;
import org.apache.wicket.protocol.http.WebResponse;

/**
 *
 * Common base page for top row of screen.
 * 
 */
public abstract class BasePage extends WebPage {

	
	public BasePage() {
		//Add create new link
		BookmarkablePageLink<String> createNew = new BookmarkablePageLink<String>( "new", MorselPage.class );
		createNew.setParameter( MorselPage.ID_PARAM, BerkeleyDataSource.CREATE_NEW_ID );
		add( createNew );
		
		//Add back to home link
		BookmarkablePageLink<String> home = new BookmarkablePageLink<String>( "home", MorselPage.class );
		home.setParameter( MorselPage.ID_PARAM, Morsel.ROOT_ID );
		add( home );
		
		//Add search panel
		add( new SearchPanel( "search" ));
		
		sendUserCookie();

		final String pageUrl = RequestCycle.get().getRequest().getURL();
	    add( new LoginLink("login", pageUrl));
	    
	    add( new LogoutLink("logout"));
	    
	    add( new UserPageLink("email"));
	    
		
	}

	//TODO: move this to a different package
	public void sendUserCookie() {
		Cookie userCookie = ((WebRequest)RequestCycle.get().getRequest()).getCookie( "user" );
		User user = MorselSession.get().getUser(); 
		if( user == null && userCookie != null  ) {
				MorselSession.get().setUser( MorselApplication.dataSource().findUserSession( userCookie.getValue() ) );
		} else if( user != null && userCookie == null ) {
			Cookie cookie = new Cookie( "user", user.getId() );
			cookie.setMaxAge( 86400*365 );
			
			String context = ((WebRequest)RequestCycle.get().getRequest()).getHttpServletRequest().getContextPath();
			if( context == null || context.length() == 0 )
				context = "/";
			cookie.setPath( context );
			((WebResponse)RequestCycle.get().getResponse()).addCookie( cookie );
		}
	}
	
	
}
